package xin.marcher.module.inventory.mq.consumer.listener;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import xin.marcher.module.common.utils.JsonUtil;
import xin.marcher.module.inventory.domain.bo.BucketCapacity;
import xin.marcher.module.inventory.service.InventoryBucketService;

import javax.annotation.Resource;
import java.util.List;

/**
 * 处理 分桶库存扩容的消息
 */
@Slf4j
@Component
public class BucketCapacityListener implements MessageListenerConcurrently {

    @Resource
    private InventoryBucketService inventoryBucketService;

    @Override
    public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
        try {
            for (MessageExt messageExt : list) {
                String msg = new String(messageExt.getBody());
                log.info("执行分桶库存扩容，消息内容：{}", msg);

                BucketCapacity bucketCapacity = JsonUtil.json2Object(msg, BucketCapacity.class);

                inventoryBucketService.bucketCapacity(bucketCapacity);
            }
        } catch (Exception e) {
            log.error("consume error, 分桶库存扩容失败", e);
            // 本次消费失败，下次重新消费
            return ConsumeConcurrentlyStatus.RECONSUME_LATER;
        }
        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
    }
}
